package com.training.admin.handler.api.impl;

import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.http.annotation.Rao;
import com.demo2do.core.utils.CollectionUtils;
import com.demo2do.core.utils.JsonUtils;
import com.training.admin.dto.Organization;
import com.training.admin.entity.department.Department;
import com.training.admin.handler.api.DepartmentApiHandler;
import com.training.admin.rao.DepartmentRao;
import com.training.admin.service.DataService;

@Component("departmentApiHandler")
public class DepartmentApiHandlerImpl implements DepartmentApiHandler {
	
	@Rao
	private DepartmentRao departmentRao;
	

	@Autowired
	private DataService<Department> departmentService;
		
	 @Value("#{config['api.host']}")
	 private String apiHost;
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.training.admin.handler.api.DepartmentApiHandler#list()
	 */
	public List<Department> list() {

		String urls = apiHost+"/idm-organizations";

		HttpResult httpResult = departmentRao.list(urls);

		if (!httpResult.isValid()) {

			throw BusinessException.newInstance(httpResult.getCode(), httpResult.getMessage());

		}


		String responseString = JsonUtils.toJson(httpResult.getData().get("organizations"));

		/*List<Department> departments = JsonUtils.parseAsList(responseString, Department.class);*/
		
		List<Organization> organizations = JsonUtils.parseAsList(responseString, Organization.class);
			
		List<Department> departments = departmentService.loadAll(Department.class);
		Map<String, Department> departmentsMap = CollectionUtils.constructMapValue(departments, "code");
		
		for(Organization organization:organizations) {
		    Department department = departmentsMap.get(organization.getOrgnofullpath());
		    if(department != null) {
		        departmentService.update(department.edit(organization));
		    }
		}
		
		return departments;

	}

}
